package com.siyoumi.app.modules.sys_code.service;

import com.siyoumi.app.entity.SysCode;
import com.siyoumi.app.service.SysCodeService;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.InputData;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class SvcCode {
    static public SvcCode getBean() {
        return XSpringContext.getBean(SvcCode.class);
    }

    static public SysCodeService getApp() {
        return SysCodeService.getBean();
    }

    /**
     * 生成随机串
     *
     * @param prefix
     */
    static public String genCode(String prefix) {
        String id01 = UUID.randomUUID().toString();
        id01 = id01.replace("-", "").substring(0, 8);

        String nanoTime = System.nanoTime() + ""; //纳秒
        String id02 = nanoTime.substring(2, 10);

        String id = id01 + id02;
        if (XStr.hasAnyText(prefix)) {
            id = prefix + id;
        }
        return id;
    }

    public JoinWrapperPlus<SysCode> listQuery(String appId, InputData inputData) {
        String key = inputData.input("key");
        String code = inputData.input("code");
        String use = inputData.input("use");

        SysCodeService svcCode = SysCodeService.getBean();
        JoinWrapperPlus<SysCode> query = svcCode.listQuery(appId);

        if (XStr.hasAnyText(code)) { // 码
            query.eq("code_code", code);
        } else {
            if (XStr.hasAnyText(key)) { // 码库
                query.eq("code_key", key);
            }
            if (XStr.hasAnyText(use)) { // 使用状态
                query.eq("code_use", use);
            }
        }

        return query;
    }


    /**
     * 删除
     */
    @SneakyThrows
    @Transactional(propagation = Propagation.MANDATORY)
    public XReturn delete(List<String> ids) {
        JoinWrapperPlus<SysCode> query = listQuery(null, InputData.getIns());
        query.in("code_id", ids);

        getApp().remove(query);

        return EnumSys.OK.getR();
    }
}
